# coding=utf-8
__author__ = 'liubin'

from flask import render_template
from flask.views import View
from flask.ext.login import login_required
from flask.ext.restful import Resource, marshal
from flask.ext.babelex import gettext as _
from project import app, User, api_view, db
from project.forms import UserForm
from resource import user_resource_fields

class UserListView(View):
    """
    用户列表的模板
    """
    methods = ['GET']
    #decorators = [login_required]

    def dispatch_request(self):
        return render_template('user/list.html')

# url指定
app.add_url_rule('/tpl/user', view_func=UserListView.as_view('tpl_userlist'))

class UserListApi(Resource):
    """
    REST:用户列表
    """
    method_decorators = [login_required]

    def get(self, **kwargs):
        data = []
        for user in User.query.all():
            data_user = {
                'id': user.id,
                'name': user.name,
                'pwd': user.pwd,
                'real_name': user.real_name
            }
            data.append(marshal(data_user, user_resource_fields))

        return {'success': True,  'data': data}

    def post(self, **kwargs):
        form = UserForm(csrf_enabled=False)
        messages = []
        data_user = {}
        if form.validate_on_submit():
            exist_user = User.query.filter_by(name=form.name.data).first()
            print(exist_user)
            if exist_user is None:
                user = User(name=form.name.data, pwd=form.pwd.data, real_name=form.real_name.data)
                db.session.add(user)
                db.session.commit()
                data_user = {
                    'id': user.id,
                    'name': user.name,
                    'pwd': user.pwd,
                    'real_name': user.real_name
                }
                return {'success': True,  'data': marshal(data_user, user_resource_fields)}
            else:
                messages.append(_('User name has been registered'))
                return {'success': False,  'messages': messages}
        else:
            messages.extend([str(error) for error in form.errors])
            return {'success': False,  'messages': messages}
api_view.add_resource(UserListApi, '/api/user', endpoint="api_userlist")

class UserView(View):
    """
    用户编辑的模板
    """
    methods = ['GET']
    #decorators = [login_required]

    def dispatch_request(self):
        return render_template('user/edit.html')
# url指定
#app.add_url_rule('/tpl/user/add', view_func=UserView.as_view('tpl_useradd'))
app.add_url_rule('/tpl/user/edit', view_func=UserView.as_view('tpl_useredit'))

class UserApi(Resource):
    """
    REST:用户
    """
    def get(self, id, **kwargs):
        messages = []
        data_user = {}
        user =  User.query.filter_by(id=id).first()
        if user:
            print(user)
            data_user = {
                    'id': user.id,
                    'name': user.name,
                    'pwd': user.pwd,
                    'real_name': user.real_name
                }
            return {'success': True,  'data': marshal(data_user, user_resource_fields)}
        else:
            messages.append(_('User is not exist'))
            return {'success': False,  'messages': messages}
    def put(self, id, **kwargs):
        messages = []
        form = UserForm(csrf_enabled=False)
        if form.validate_on_submit():
            user =  User.query.filter_by(id=id).first()
            if user:
                user.name = form.name.data
                user.real_name = form.real_name.data
                user.pwd = form.pwd.data
                db.session.commit()
                return {'success': True}
            else:
                messages.append(_('User is not exist'))
                return {'success': False,  'messages': messages}
        else:
            messages.extend([str(error) for error in form.errors])
            return {'success': False,  'messages': messages}

    def delete(self, id, **kwargs):
        messages = []
        user =  User.query.filter_by(id=id).first()
        if user:
            db.session.delete(user)
            db.session.commit()
            return {'success': True}
        else:
            messages.append(_('User is not exist'))
            return {'success': False,  'messages': messages}

api_view.add_resource(UserApi, '/api/user/<int:id>', endpoint="api_user")

